#include "../Multi_UDP_Client/Multi_UDP_Client.h"

void Multi_UDP_ClientAPI()
{
  const size_t BufSize=1024;
  char recvBuf[BufSize];

  //加载Windows环境
  WORD ver = MAKEWORD(2, 2);
  WSADATA dat;
  WSAStartup(ver, &dat);

  //创建socket
  SOCKET Client_sock = socket(AF_INET, SOCK_DGRAM, 0);
  if (-1 == Client_sock) {
    printf("Build UDP_client's socket failed!!!\n");
  }
  else {
    printf("Build UDP_client's socket successful...\n");
  }

  //设置端口复用
  int bOptval = 1;
  int retSetsockopt = setsockopt(Client_sock, SOL_SOCKET, SO_REUSEADDR, (char *)&bOptval, sizeof(bOptval));

  //绑定本地信息
  sockaddr_in Local_sin = {};
  Local_sin.sin_family = AF_INET;
  Local_sin.sin_port = htons(9999);
  Local_sin.sin_addr.s_addr = INADDR_ANY;

  if(bind(Client_sock, (sockaddr *)&Local_sin, sizeof(Local_sin)) == -1) {
       perror("bind");
       exit(-1);
  }
  //加入组播组
  ip_mreq multi_sin;
  inet_pton(AF_INET, MULTI_UDP_IP, &multi_sin.imr_multiaddr.s_addr);
  multi_sin.imr_interface.s_addr = INADDR_ANY;
  setsockopt(Client_sock, IPPROTO_IP, IP_ADD_MEMBERSHIP,(char *)&multi_sin, sizeof(multi_sin));

  sockaddr_in Server_sock;
  socklen_t len=sizeof(Server_sock);

  //缓冲区
  while (true) {
    int nlen = recvfrom(Client_sock, recvBuf, sizeof(recvBuf), 0, (SOCKADDR*)&Server_sock, &len);
    printf("%d", nlen);

    if (nlen > 0)
    {
      recvBuf[nlen] = '\0';      //给字符数组加一个'\0'，表示结束了。不然输出有乱码
      if (strcmp(recvBuf, "bye") == 0)
      {
        printf("Server close!!!");//当服务器发来bye时，关闭socket
        closesocket(Client_sock);
        break;
      }
      else
      {
        printf("Recv message sucessful : %s\n", recvBuf);
      }
    }
    memset(recvBuf, 0, sizeof(recvBuf));
  }
  //关闭客户端连接
  closesocket(Client_sock);
  //
  WSACleanup();
  printf("Client closed...");
  getchar();
}